document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    const phoneInput = document.getElementById('phone');
    const passwordInput = document.getElementById('password');
    const togglePassword = document.querySelector('.toggle-password');
    const rememberCheckbox = document.getElementById('remember');
    const phoneError = document.getElementById('phoneError');
    const passwordError = document.getElementById('passwordError');

    // 切换密码显示/隐藏
    togglePassword.addEventListener('click', function() {
        const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        passwordInput.setAttribute('type', type);
        this.classList.toggle('fa-eye');
        this.classList.toggle('fa-eye-slash');
    });

    // 手机号验证
    function validatePhone(phone) {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phone);
    }

    // 显示错误信息
    function showError(element, message) {
        element.textContent = message;
        element.style.display = 'block';
    }

    // 清除错误信息
    function clearError(element) {
        element.textContent = '';
        element.style.display = 'none';
    }

    // 实时验证手机号
    phoneInput.addEventListener('input', function() {
        clearError(phoneError);
        if (this.value && !validatePhone(this.value)) {
            showError(phoneError, '请输入正确的手机号码');
        }
    });

    // 表单提交处理
    loginForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        // 清除之前的错误信息
        clearError(phoneError);
        clearError(passwordError);

        // 获取表单数据
        const phone = phoneInput.value.trim();
        const password = passwordInput.value.trim();

        // 验证手机号
        if (!validatePhone(phone)) {
            showError(phoneError, '请输入正确的手机号码');
            return;
        }

        // 验证密码
        if (!password) {
            showError(passwordError, '请输入密码');
            return;
        }

        try {
            // 发送登录请求到user模块后端
            const response = await fetch('http://localhost:8080/api/users/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    phone,
                    password
                })
            });

            const data = await response.json();

            if (response.ok) {
                // 登录成功
                // 保存token和用户信息
                const user = data.data;
                
                if (rememberCheckbox.checked) {
                    // 如果选择了"记住我"，将用户信息存储在localStorage
                    localStorage.setItem('user', JSON.stringify(user));
                } else {
                    // 否则存储在sessionStorage
                    sessionStorage.setItem('user', JSON.stringify(user));
                }

                // 显示成功消息
                alert('登录成功！');
                
                // 跳转到首页
                window.location.href = 'home.html';
            } else {
                // 登录失败
                showError(passwordError, data.message || '登录失败，请检查账号密码');
            }
        } catch (error) {
            console.error('登录错误:', error);
            showError(passwordError, '登录失败，请稍后重试');
        }
    });

    // 检查是否有保存的登录信息
    window.addEventListener('load', function() {
        const savedPhone = localStorage.getItem('phone');
        if (savedPhone) {
            phoneInput.value = savedPhone;
            rememberCheckbox.checked = true;
        }
    });
});